package cn.edu.hfut.dmic.webcollector.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import cn.edu.hfut.dmic.webcollector.util.Config;

public class HttpRequesterJsonImpl{

	public static final Logger LOG = LoggerFactory
			.getLogger(HttpRequesterJsonImpl.class);
	protected Proxys proxys = null;
	protected String userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0";
	protected String cookie = null;

	public void configConnection(HttpURLConnection con) {

	}

	public JSONObject getResponse(String url) throws Exception {
		JSONObject jsonObject = null;
		StringBuilder response = new StringBuilder();
		HttpURLConnection con = null;
		URL _URL = new URL(url);
		int code = -1;
		int maxRedirect = Math.max(0, Config.MAX_REDIRECT);
		for (int redirect = 0; redirect <= maxRedirect; redirect++) {
			if (proxys == null) {
				con = (HttpURLConnection) _URL.openConnection();
			} else {
				Proxy proxy = proxys.nextProxy();
				if (proxy == null) {
					con = (HttpURLConnection) _URL.openConnection();
				} else {
					con = (HttpURLConnection) _URL.openConnection(proxy);
				}
			}
			if (userAgent != null) {
				con.setRequestProperty("User-Agent", userAgent);
			}
			if (cookie != null) {
				con.setRequestProperty("Cookie", cookie);
			}
			con.setInstanceFollowRedirects(false);
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setConnectTimeout(10000);
			con.setReadTimeout(10000);

			configConnection(con);
			con.connect();
			code = con.getResponseCode();

			boolean needBreak = false;
			switch (code) {
			case HttpURLConnection.HTTP_MOVED_PERM:
			case HttpURLConnection.HTTP_MOVED_TEMP:
				if (redirect == Config.MAX_REDIRECT) {
					throw new Exception("redirect to much time");
				}
				String location = con.getHeaderField("Location");
				if (location == null) {
					throw new Exception("redirect with no location");
				}
				String originUrl = _URL.toString();
				_URL = new URL(_URL, location);
				LOG.info("redirect from " + originUrl + " to " + _URL.toString());
				continue;
			default:
				needBreak = true;
				break;
			}
			if (needBreak) {
				break;
			}

		}

		InputStream is;
		is = con.getInputStream();
		String contentEncoding = con.getContentEncoding();
		if (contentEncoding != null && contentEncoding.equals("gzip")) {
			is = new GZIPInputStream(is);
		}

		BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("utf-8")));   
        String readLine = null;   
        while((readLine =br.readLine()) != null){   
            response.append(readLine);   
        }   
        if(is != null){
        	is.close(); 
        }
        if(br != null){
        	br.close();  
        }
        if(con != null){
			con.disconnect();
		}
        String str = response.toString();
		LOG.info(str);
		jsonObject = new JSONObject(str.substring(str.indexOf("{"), str.lastIndexOf("}") + 1));
		return jsonObject;
	}

	public String getUserAgent() {
		return userAgent;
	}

	public void setUserAgent(String userAgent) {
		this.userAgent = userAgent;
	}

	public String getCookie() {
		return cookie;
	}

	public void setCookie(String cookie) {
		this.cookie = cookie;
	}

	public Proxys getProxys() {
		return proxys;
	}

	public void setProxys(Proxys proxys) {
		this.proxys = proxys;
	}
}
